const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const User = require('../models/User');

// 用户注册
router.post('/register/users', async(req, res) => {
    try {
        const { username, password } = req.body;

        // 检查用户是否已存在
        const existingUser = await User.findOne({ username });
        if (existingUser) {
            return res.status(400).json({
                code: 400,
                msg: '用户名已存在',
                data: null
            });
        }

        // 创建新用户
        const user = new User({ username, password });
        await user.save();

        // 生成 token
        const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '24h' });

        res.status(201).json({
            code: 200,
            msg: '注册成功',
            data: {
                token,
                id: user._id,
                username: user.username
            }
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '注册失败',
            data: null,
            error: error.message
        });
    }
});

// 用户登录
router.post('/login/users', async(req, res) => {
    try {
        const { username, password } = req.body;

        // 查找用户
        const user = await User.findOne({ username });
        if (!user) {
            return res.status(401).json({
                code: 401,
                msg: '用户名或密码错误',
                data: null
            });
        }

        // 验证密码
        const isMatch = await user.comparePassword(password);
        if (!isMatch) {
            return res.status(401).json({
                code: 401,
                msg: '用户名或密码错误',
                data: null
            });
        }

        // 生成 token
        const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '24h' });

        res.json({
            code: 200,
            msg: '登录成功',
            data: {
                token,
                id: user._id,
                username: user.username,
                theme: user.theme
            }
        });
    } catch (error) {
        res.status(500).json({
            code: 500,
            msg: '登录失败',
            data: null,
            error: error.message
        });
    }
});

module.exports = router;